package com.weixing.mall.provider.controller.act;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.provider.api.model.dto.MemberMessageDto;
import com.weixing.mall.provider.api.model.enums.ActTypeEnum;
import com.weixing.mall.provider.api.service.AgentProfitFeign;
import com.weixing.mall.provider.api.service.LeaveMessageServiceRpc;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.model.domain.Activity;
import com.weixing.mall.provider.model.dto.act.ActivityDto;
import com.weixing.mall.provider.model.enums.IsPublishEunm;
import com.weixing.mall.provider.model.enums.act.ActStatusEnum;
import com.weixing.mall.provider.model.enums.act.IsPublish;
import com.weixing.mall.provider.model.enums.act.SettleStatusEnum;
import com.weixing.mall.provider.model.enums.act.ShowClientEnum;
import com.weixing.mall.provider.model.query.ActivityQuery;
import com.weixing.mall.provider.model.vo.act.ActivityVo;
import com.weixing.mall.provider.service.IActivityService;
import com.weixing.mall.provider.service.ISeckillImportService;
import com.weixing.mall.provider.support.excel.act.SeckillOrderImportCopyData;
import com.weixing.mall.provider.support.excel.act.SeckillOrderImportListener;
import com.weixing.mall.push.GtComponent;
import com.weixing.mall.push.PushMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 管理端活动相关接口
 *
 * @author  siashan
 * @date  2019/10/16 15:27
 * @since  1.0
 **/
@RestController
@RequestMapping("act")
@Api(value = "活动模块API", tags = "商城活动")
public class ActivityController extends BaseController {
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ISeckillImportService seckillImportService;
    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private AgentProfitFeign agentProfitFeign;
    @Autowired
    private GtComponent gtComponent;
    @Autowired
    private LeaveMessageServiceRpc leaveMessageServiceRpc;

    /**
     * 加载活动列表
     * @param query  查询条件
     * @return 活动列表
     */
    @GetMapping("")
    public Result list(ActivityQuery query) {
        IPage<ActivityVo> pageInfo = activityService.findList(initMpPage(), query);
        List<ActivityVo> records = pageInfo.getRecords();
        if (CollUtil.isNotEmpty(records)){
            for (ActivityVo vo : records){
                vo.setCanPlace(vo.canPlace());
            }
        }
        return ResultUtil.success(pageInfo);
    }

    /**
     * 加载会员活动列表
     * @param query 查询条件
     * @return 活动列表
     */
    @GetMapping("/memnerList")
    public Result<List<ActivityVo>> memnerList(ActivityQuery query) {
        List<ActivityVo> pageInfo = activityService.memnerList(query);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 保存活动
     *
     * @param dto  参数
     * @return 保存结果
     */
    @PostMapping("save")
    @NoRepeatSubmit
    public Result save(@Validated ActivityDto dto) {
       boolean result= activityService.checkActCode(dto.getActCode());
       if(!result){
           return ResultUtil.error("活动编码不符合规则！");
       }
        activityService.save(dto);
        return ResultUtil.success();
    }

    /**
     * 活动详情
     *
     * @param id  活动id
     * @return  活动详情
     */
    @PostMapping("{id}")
    @NoRepeatSubmit
    public Result<ActivityVo> getById(@PathVariable Long id) {
        Activity activity = activityService.getById(id);
        ActivityVo activityVo = new ActivityVo();
        BeanUtils.copyProperties(activity, activityVo);
        activityVo.setIsPublish(EnumUtil.getIEnum(IsPublishEunm.class, activity.getIsPublish()));
        activityVo.setActStatus(EnumUtil.getIEnum(ActStatusEnum.class, activity.getActStatus()));
        activityVo.setSettleStatus(EnumUtil.getIEnum(SettleStatusEnum.class, activity.getSettleStatus()));
        activityVo.setActType(EnumUtil.getIEnum(ActTypeEnum.class, activity.getActType()));
        activityVo.setShowClient(EnumUtil.getIEnum(ShowClientEnum.class, activity.getShowClient()));
        activityVo.setIsDayAct(EnumUtil.getIEnum(WhetherEnum.class, activity.getIsDayAct()));
        return ResultUtil.success(activityVo);
    }

    /**
     * 删除活动
     *
     * @param id 活动id
     * @return 返回结果
     */
    @PostMapping("del/{id}")
    public Result del(@PathVariable(value = "id") long id) {
        Activity activity = activityService.getById(id);
        if (null != activity) {
            if (ActStatusEnum.NOT_START.getValue().equals(activity.getActStatus())) {
                return activityService.removeById(id) != false ? ResultUtil.success() : ResultUtil.error();
            } else {
                return ResultUtil.error("活动已开始不允许删除");
            }

        }
        return ResultUtil.error("活动不存在");
    }


    @ApiOperation(value = "查询活动-用于表单操作")
    @GetMapping("form")
    public Result activity(ActTypeEnum actType) {
        return ResultUtil.success(activityService.selectActivityFormVoList(actType));
    }

    /**
     * 发布活动
     * @param id
     * @return
     */
    @ApiOperation(value = "发布活动")
    @PostMapping("publish/{id}")
    public Result publish(@PathVariable(value = "id") long id) {
        Activity activity = activityService.getById(id);
        if (null != activity) {
            if (IsPublish.NOT_PUBLISH.getValue().equals(activity.getIsPublish())) {
                activity.setIsPublish(IsPublish.IS_PUBLISH.getValue());
                activity.setActStatus(ActStatusEnum.ONGOING.getValue());
                boolean b = activityService.updateById(activity);
                if (b){
                    String content = "活动名称：" + activity.getActName() + "，活动开始时间：" + DateUtil.format(activity.getStartTime(), DatePattern.NORM_DATE_PATTERN);
                    MemberMessageDto memberMessage = new MemberMessageDto();
                    memberMessage.setTitle("新活动通知");
                    memberMessage.setMsg(content);
                    memberMessage.setMsgType(1);
                    leaveMessageServiceRpc.createMsg(memberMessage);
                    // TODO 推送活动消息
                    PushMsg pushMsg = new PushMsg();
                    pushMsg.setTitle("新活动通知");
                    pushMsg.setBody(content);
                    pushMsg.setClick_type("none");

                    gtComponent.pushAll(pushMsg);
                }
                return b != false ? ResultUtil.success() : ResultUtil.error();

            } else {
                return ResultUtil.error("已经发布");
            }

        }
        return ResultUtil.error("活动不存在");
    }

    @ApiOperation(value = "后台有效活动菜单")
    @PostMapping("activityList")
    public Result activityList(Integer  flag) {
        Date dateTime = DateUtil.offset(new Date(), DateField.YEAR, -1);
        List<ActivityVo> activityVos = activityService.selectDataList(dateTime,flag);
        if (CollUtil.isNotEmpty(activityVos)){
            for (ActivityVo vo : activityVos){
                vo.setCanPlace(vo.canPlace());
            }
        }
        return ResultUtil.success(activityVos);
    }

    @ApiOperation(value = "每日活动菜单")
    @PostMapping("dayList")
    public Result dayList() {
        return ResultUtil.success(activityService.dayList(WhetherEnum.YES.getValue()));
    }

    @ApiOperation(value = "后台无效活动菜单")
    @PostMapping("invitedList")
    public Result invitedList() {
        Date dateTime = DateUtil.offset(new Date(), DateField.YEAR, -1);
        return ResultUtil.success(activityService.selectinvitedList(dateTime));
    }


    @ApiOperation(value = "预刷新活动商品库存到redis")
    @PostMapping("refreshStockInRedis/{actId}")
    public Result refreshStockInRedis(@PathVariable Long actId) {
        activityService.refreshStockInRedis(actId);
        return ResultUtil.success();
    }


    @ApiOperation(value = "活动结束将商品库存从redis释放")
    @PostMapping("delStockFromRedis/{actId}")
    public Result delStockFromRedis(@PathVariable Long actId) {
        activityService.delStockFromRedis(actId);
        return ResultUtil.success();
    }


    @ApiOperation(value = "秒杀活动代理订单导入")
    @PostMapping("seckillOrderImport/{actId}")
    public Result seckillOrderImport(@PathVariable Long actId, MultipartFile file) {
        return execImport(actId, file,SeckillOrderImportListener.ROLE_AGENT);
    }



    @ApiOperation(value = "秒杀活动客服订单导入")
    @PostMapping("seckillOrderImportForKefu/{actId}")
    public Result seckillOrderImportForKefu(@PathVariable Long actId, MultipartFile file) {
        return execImport(actId, file,SeckillOrderImportListener.ROLE_KEFU);
    }


    @ApiOperation(value = "活动结算")
    @PostMapping("settle/{actId}")
    public Result actSettle(@PathVariable Long actId) {
        activityService.delStockFromRedis(actId);
        Result result = agentProfitFeign.actCalcProfit(actId);
        if (!result.isSuccess()) {
            return result;
        }
        return ResultUtil.success();
    }

    private Result execImport(@PathVariable Long actId, MultipartFile file,Integer role) {
        Activity byId = activityService.getById(actId);
        if (SettleStatusEnum.SETTLE_SUCCESS.getValue().equals(byId.getSettleStatus())) {
            return ResultUtil.error("活动已结算，禁止导入");
        }
        try {
            EasyExcel.read(file.getInputStream(), SeckillOrderImportCopyData.class, new SeckillOrderImportListener(byId, orderServiceRpc, seckillImportService,role)).sheet().headRowNumber(2).doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        // 记录导入记录

        return ResultUtil.success();
    }

}
